package com.metel.mservice.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

/**
 * StaticResourceReader
 * 
 * @author sr80.choi
 */
public class StaticResourceReader {

	private Map<String, byte[]> cache;

	public void initializeMap() {
		HashMap<String, byte[]> hashMap = new HashMap<String, byte[]>();

		cache = Collections.synchronizedMap(hashMap);
	}

	/**
	 * return byte array from static resource
	 * 
	 * @param resourceName
	 * @param servletContext
	 * @return
	 */
	public byte[] getResourceAsStream(String resourceName, ServletContext servletContext) {
		byte[] resource = null;

		// read resource
		if (cache.containsKey(resourceName)) {
			// from cache
			resource = cache.get(resourceName);
		} else {
			// read webapp and then caching
			resource = getResource(resourceName, servletContext);

			cache.put(resourceName, resource);
		}

		return resource;
	}

	private byte[] getResource(String resourceName, ServletContext servletContext) {
		InputStream is = findResource(resourceName, servletContext);

		byte[] b = null;
		try {
			b = new byte[is.available()];
			is.read(b);
		} catch (Exception e) {
			b = null;
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
			} finally {
				is = null;
			}
		}

		return b;
	}

	private InputStream findResource(String resourceName, ServletContext servletContext) {
		InputStream is = null;

		String path = "";
		if (!resourceName.startsWith("/")) {
			path = "/";
		}
		path += resourceName;

		// scan webapp
		is = servletContext.getResourceAsStream(path);

		// scan classpath
		if (is == null) {
			is = StaticResourceReader.class.getResourceAsStream(path);
		}

		return is;
	}
}
